package shuaige.jdk.多线程.concurrent.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class 创建CompletableFuture对象 {

    private ExecutorService executor = Executors.newFixedThreadPool(3);

    public static void main(String[] args) {
        创建CompletableFuture对象 创建CompletableFuture对象 = new 创建CompletableFuture对象();
        创建CompletableFuture对象.立即返回结果();
    }

    public void 立即返回结果() {
        // 返回一个已经计算好的值
        CompletableFuture<String> f0 = CompletableFuture.completedFuture("return value");
        System.out.println(f0.join());
    }

    public void 异步处理任务_没有返回值() {
        // 异步处理任务,没有返回值
        CompletableFuture<Void> f1 = CompletableFuture.runAsync(System.out::println);
        // 异步处理任务,没有返回值，使用指定
        CompletableFuture<Void> f2 = CompletableFuture.runAsync(System.out::println, executor);
    }

    public void 异步处理任务_有返回值() {
        // 异步处理任务,有返回值
        CompletableFuture<String> f3 = CompletableFuture.supplyAsync(this::get);
        CompletableFuture<String> f4 = CompletableFuture.supplyAsync(this::get, executor);
    }

    public String get() {
        delay();
        return "异步任务结果";
    }

    public void delay() {
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
